package cn.iocoder.yudao.module.digital.controller.admin.cardkeysecret;

import cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;
import cn.iocoder.yudao.framework.operatelog.core.annotations.OperateLog;
import cn.iocoder.yudao.framework.security.core.annotations.PreAuthenticated;
import cn.iocoder.yudao.module.digital.api.cardkeymanager.dto.CardKeySecretDTO;
import cn.iocoder.yudao.module.digital.controller.admin.cardkeysecret.vo.*;
import cn.iocoder.yudao.module.digital.dal.dataobject.cardkeysecret.CardkeySecretDO;
import cn.iocoder.yudao.module.digital.enums.ErrorCodeConstants;
import cn.iocoder.yudao.module.digital.framework.cardkey.config.CardKeyConfig;
import cn.iocoder.yudao.module.digital.service.cardchannel.ICardSecretManager;
import cn.iocoder.yudao.module.digital.service.cardkeysecret.CardkeySecretService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.List;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.operatelog.core.enums.OperateTypeEnum.EXPORT;

@Tag(name = "管理后台 - 卡密密钥")
@RestController
@RequestMapping("/digital/cardkey-secret")
@Validated
public class CardkeySecretController {

    @Resource
    private CardkeySecretService cardkeySecretService;
    @Resource
    private ICardSecretManager cardSecretManager;
    @Resource
    private CardKeyConfig cardKeyConfig;

    @GetMapping("/get")
    @Operation(summary = "获得卡密密钥")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('digital:cardkey-secret:query')")
    public CommonResult<CardkeySecretRespVO> getCardkeySecret(@RequestParam("id") String id) {
        CardkeySecretDO cardkeySecret = cardkeySecretService.getCardkeySecret(id);
        return success(BeanUtils.toBean(cardkeySecret, CardkeySecretRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得卡密密钥分页")
    @PreAuthorize("@ss.hasPermission('digital:cardkey-secret:query')")
    public CommonResult<PageResult<CardkeySecretRespVO>> getCardkeySecretPage(@Valid CardkeySecretPageReqVO pageReqVO) {
        PageResult<CardkeySecretDO> pageResult = cardkeySecretService.getCardkeySecretPage(pageReqVO);
        return success(BeanUtils.toBean(pageResult, CardkeySecretRespVO.class));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出卡密密钥 Excel")
    @PreAuthorize("@ss.hasPermission('digital:cardkey-secret:export')")
    @OperateLog(type = EXPORT)
    public void exportCardkeySecretExcel(@Valid CardkeySecretPageReqVO pageReqVO,
                                         HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<CardkeySecretDO> list = cardkeySecretService.getCardkeySecretPage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "卡密密钥.xls", "数据", CardkeySecretRespVO.class,
                BeanUtils.toBean(list, CardkeySecretRespVO.class));
    }

    @PostMapping("/claim-secret-by-customer-service")
    @Operation(summary = "领取卡密-通过客服")
    @PreAuthorize("@ss.hasPermission('digital:cardkey-secret:create')")
    public CommonResult claimCardKeySecretByCustomerService(@Valid @RequestBody ClaimSecretByCustomerServiceReqVo reqVo) {
        cardSecretManager.claimCardKeySecretByCustomerService(reqVo.getOrderNo(), reqVo.getSecret());
        return success(null);
    }

    @PostMapping("/claim-secret-by-user")
    @Operation(summary = "领取卡密-通过用户")
    @PreAuthorize("@ss.hasPermission('digital:cardkey-secret:create')")
    public CommonResult claimCardKeySecret(@Valid @RequestBody ClaimSecretByUserReqVo reqVo) {
        final Boolean mockOrder = cardKeyConfig.getMockOrder();
        if (!mockOrder) {
            throw ServiceExceptionUtil.exception(ErrorCodeConstants.CARDKEY_DEFAULT_ERROR, "无权限操作（领取卡密-通过用户）");
        }
        cardSecretManager.preprocessCardKeyShipping(reqVo.getOrderNo(), reqVo.getSkuId(), reqVo.getSkuNum(), reqVo.getBuyDenomination());
        return success(null);
    }

    @PostMapping("/preview")
    @Operation(summary = "预览密钥")
    @PreAuthorize("@ss.hasPermission('digital:cardkey-secret:query')")
    public CommonResult<List<CardkeySecretPreviewRespVO>> previewSecret(@Valid @RequestBody CardkeySecretPreviewReqVO reqVO) {
        final List<CardKeySecretDTO> cardKeySecretDTOS = cardSecretManager.parseCardSecretData(reqVO.getSecret());
        final List<CardkeySecretPreviewRespVO> voList = BeanUtils.toBean(cardKeySecretDTOS, CardkeySecretPreviewRespVO.class);
        return success(voList);
    }

    @Deprecated
    @GetMapping("/get-by-order-no")
    @Operation(summary = "查询卡密密钥-通过订单号")
    @Parameter(name = "orderNo", description = "订单流水号", required = true, example = "1024")
    @PreAuthenticated
    public CommonResult<List<CardkeySecretPreviewRespVO>> getCardkeySecretByOrderNo(@RequestParam("orderNo") String orderNo) {
        final List<CardkeySecretDO> secretDOList = cardkeySecretService.getCardKeySecretByOrderNo(orderNo);
        return success(BeanUtils.toBean(secretDOList, CardkeySecretPreviewRespVO.class));
    }


}